/*CREAT BY SHEN ON 2017/10/28*/
accessid = 'LTAIeSuPvTTZ2w3e';
accesskey = 'OEU0c1OxJVGwuz75hBzU9jA0nBaLca';
host = 'http://shen-xiaoyong.oss-cn-shenzhen.aliyuncs.com';
var rename_host="http://shen-xiaoyong.oss-cn-shenzhen.aliyuncs.com/"
g_dirname = ''
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;
var finalFileUrl = rename_host + "/";
var suffixName = '';
var beforFileName = '';
var policyText = {
    "expiration": "2020-01-01T12:00:00.000Z", // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
        ["content-length-range", 0, 10485760]// 设置上传文件的大小限制//1048576000
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {asBytes: true});
var signature = Crypto.util.bytesToBase64(bytes);

function check_object_radio() {
    g_object_name_type = 'random_name';
}

function get_dirname() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var strDate = year + "-" + month + "-" + day
    // 存放阿里云的文件夹
    g_dirname = "img/users/" + strDate + "/";
}

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    suffixName = suffix
    return suffix;
}

function calculate_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name') {
        suffix = get_suffix(filename)
        g_object_name = g_dirname + random_string(10) + suffix
        finalFileUrl = rename_host + "/";
        finalFileUrl += g_object_name
    }
    return ''
}

function get_uploaded_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if (g_object_name_type == 'random_name') {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret) {
    g_object_name = g_dirname;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', // 让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
    up.start();
}


//触发的id
var ids = new Array("addUser");
$.each(ids, function (i, n) {
    var self = this.toString();
    //实例化一个plupload上传对象
    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: self,
        multi_selection: false,
        container: document.getElementById(self + "Container"),
        flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
        silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
        url: 'http://oss.aliyuncs.com',
    });
    //在实例对象上调用init()方法进行初始化
    uploader.init();
    //绑定各种事件，并在事件监听函数中做你想做的事
    uploader.bind('FilesAdded', function (uploader, files) {
        $("#" + self + "Ossfile").show();
        plupload.each(files, function (file) {
            var name = file.name
            beforFileName = name;
            var ks = 20
            if (name.length > ks)
                name = "..." + name.substring(name.length - ks, name.length);
            $("#h5upload_fileName").text(name + "(" + plupload.formatSize(file.size) + ")")
            $("#h5upload_percent").text("0%")
            $("#" + self + "Ossfile").each(function () {
                $(this).attr("display", "block")
                var ks = $(this).html();
                ks += '<div class="' + file.id + '">' + name + " " + "(" + plupload.formatSize(file.size) + ")"
                    + '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                    + '</div>';
                $(this).html(ks);
                set_upload_param(uploader, '', false);
                return false;
            })
        });
    });
    uploader.bind('BeforeUpload', function (uploader, files) {
        check_object_radio();
        get_dirname();
        set_upload_param(uploader, files.name, true);
    });
    uploader.bind('UploadProgress', function (uploader, files) {
        var d = $("#" + self + "Ossfile");
        $("." + files.id + " .progress-bar").each(function () {
            $(this).attr("style", "width:" + files.percent + "%");
        })
    });
    uploader.bind('FileUploaded', function (uploader, files, info) {
        if (info.status == 200) {
            if (!(suffixName == ".jpg" || suffixName == ".JPG" || suffixName == ".png" || suffixName == ".PNG" || suffixName == ".jpeg" || suffixName == ".JPEG" || suffixName == ".gif" || suffixName == ".GIF" || suffixName == ".bmp" || suffixName == ".BMP")) {
                $.alert("请选择图片文件");
            } else {
                $("#" + self + "Pic").attr("src", finalFileUrl);
            }
            $("#" + self + "Ossfile").fadeOut(1000, function () {
                $(this).html("");
            });
        }
        else {
            document.getElementById(files.id).getElementsByTagName('b')[0].innerHTML = info.response;
        }
    });
    uploader.bind('FileUpload', function (uploader, files, info) {
        if (info.status == 200) {
            $("#" + self + "Pic").attr("src", finalFileUrl);
            $("#" + self + "Ossfile").fadeOut(1000, function () {
                $(this).html("");
            });
        }
        else {
            document.getElementById(files.id).getElementsByTagName('b')[0].innerHTML = info.response;
        }
    });
});